# 肯德基网站写入MYSQL
import pymysql
import requests

class kendeji(object):
    # 1.配置信息
    def __init__(self):
        # 在1146 之前就应该在MYSQL中创建"kendeji"数据库
        self.db = pymysql.connect(host="localhost", user="root", password="2743YZL,", db="kendeji")
        self.cursor = self.db.cursor()
        # 获取资源地址
        self.url = "https://www.kfc.com.cn/kfccda/ashx/GetStoreList.ashx?op=cname"
        self.headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
            "Cookie": "__utmz=62931061.1732767443.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); __utma=62931061.806578909.1732767443.1732767443.1733278636.2; route-cell=ksa; ASP.NET_SessionId=gjprwjdthpektzjoaioxq4oi; VOLCALBCORS=5065c71485bb7361a81e5558302cee16|1734097661|1734097537; VOLCALB=5065c71485bb7361a81e5558302cee16|1734097661|1734097537",
        }


    # 3.创建表函数
    def create_table(self):
        sql = """
            CREATE TABLE IF NOT EXISTS kendeji(
                id int primary key auto_increment not null, 
                storeName VARCHAR(255) NOT NULL,
                pro VARCHAR(255) NOT NULL,
                addressDetail TEXT)
            """
        try:
            self.cursor.execute(sql)
            print("CREATE TABLE SUCCESS")
        except Exception as ex:
            print(f"CREATE TABLE FAILED, CASE:{ex}")

    # 2.发送请求
    def get_data(self, page):
        params = {
            "cname":"湘潭",
            "pid":"",
            "pageIndex":page,
            "pageSize":"10"
        }
        response = requests.post(url=self.url, headers=self.headers, params=params)
        return response.json()

    # 4.解析数据
    def params_data(self, response):
        data_list = response["Table1"]
        for i in data_list:
            storeName = i["storeName"]
            addressDetail= i["addressDetail"]
            pro = i["pro"]
            self.save_data(storeName, addressDetail, pro)


    # 5.存储数据（表中）
    def save_data(self,storeName, addressDetail, pro):
        # 插入的语
        sql = 'INSERT INTO kendeji(id, storeName , addressDetail, pro) values({}, "{}", "{}", "{}")'.format(0, storeName , addressDetail, pro)
        # 执行sql 语句
        try:
            self.cursor.execute(sql)
            # 提交到数据库执行
            self.db.commit()
            print("数据插入成功...")
        except Exception as e:
            print(f"数据插入失败：{e}")
            # 如果 发生错误就回滚
            self.db.rollback()

    # 6.程序入口
    def main(self):
        self.create_table()
        for i in range(1, 10):
            response = self.get_data(i)
            self.params_data(response)

        self.db.close()

# 7. 执行函数
if __name__ == "__main__":
    bd = kendeji()
    bd.main()
